#!/bin/bash
#
# manage a group of: gateway + n*game + world

prog="node"
server=""

RETVAL=0
_start() {
    name=$1
    args=$2
    pidfile="$1.pid"

    echo -n $"Starting $name .............."
    if [ -f $pidfile ]; then
        echo -e "\t\E[31;40m[FAIL]\033[0m"
        echo "$name is Running"
    else
        $prog $args 1>/dev/null &
        for i in {1..5}; do
            if [ -f $pidfile ]; then
                echo -e "\t\E[32;40m[OK]\033[0m"
                break
            else
                if [ $i -eq 5 ]; then
                    echo -e "\t\E[31;40m[FAIL]\033[0m"
                fi
            fi
            sleep 1
        done
    fi
    RETVAL=$?
}

_stop() {
    name=$1
    pidfile="$1.pid"

    echo -n $"Stopping $name .............."
    if [ -f ${pidfile} ]; then
        pid=`cat ${pidfile}`
        if [ -d "/proc/${pid}" ]; then
            while [ -d "/proc/${pid}" ]; do
                kill  ${pid}
                sleep 1
            done
        fi
        rm -f ${pidfile}
    fi
    echo -e "\t\E[32;40m[OK]\033[0m"
    RETVAL=$?
}

_status() {
    name=$1
    pidfile="$1.pid"

    echo -n -e "$name\t\t"
    if [ -f ${pidfile} ]; then
        pid=`cat ${pidfile}`
        echo -n -e "$pid\t\t"
        if [ -d "/proc/${pid}" ]; then
            echo -n -e "\E[32;40m[Running]\033[0m\t"
        else
            echo -n -e "\E[31;40m[Lost]\033[0m\t\t"
        fi

        echo `ps -p $pid -o rss | tail -n 1 | awk '{printf("%.2fM", $1/1024)}'`
    else
        echo -e "-\t\t\E[31;40m[Stoped]\033[0m\t-"
    fi

    RETVAL=$?
}

start() {
    if [ "$server" =  "gateway" ] || [ "$server" = "" ]; then
        _start gateway 'gateway.js'
    fi

    if [ "$server" =  "game" ] || [ "$server" = "" ]; then
        _start game 'game.js'
    fi

}

stop() {
    if [ "$server" =  "gateway" ] || [ "$server" = "" ]; then
        _stop gateway
    fi
    if [ "$server" =  "game" ] || [ "$server" = "" ]; then
        _stop game
    fi
}

status() {
    echo -e "Version: `git log | head -n 1 | awk '{print $2}'`"
    echo "------------------------------------------------------"
    echo -e "Process\t\tPID\\t\tStatus\t\tMem"


    if [ "$server" =  "gateway" ] || [ "$server" = "" ]; then
        _status gateway
    fi
    if [ "$server" =  "game" ] || [ "$server" = "" ]; then
        _status game
    fi
}

if [ $# -ge 2 ]; then
    case "$2" in
        gateway|game)
            server=$2
            ;;
        *)
            echo "arg 2 should in [gateway|game]"
            exit 1
    esac
fi

# See how we were called.
case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  status)
        status
        ;;
  restart)
        stop
        start
        ;;
  *)
        echo $"Usage: manage {start|stop|restart|status} [gateway|game]"
        exit 1
esac

exit $RETVAL
